import React, { useState, useEffect } from 'react';
import { PageContainer, ProCard } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Row, Col, Statistic, Card, Alert, Typography, Space, Button } from 'antd';
import {
  UserOutlined,
  BookOutlined,
  FileTextOutlined,
  BarChartOutlined,
  TrophyOutlined,
  ClockCircleOutlined,
  EyeOutlined,
  HeartOutlined
} from '@ant-design/icons';

// 引入图表组件
import { EchartsLine, EchartsColumn, EchartsPie, EchartsArea } from '@/components/Charts';

// 引入API服务
import {
  getUserStatistics,
  getCourseStatistics,
  getContentStatistics,
  getSystemStatistics
} from '@/services/statisticsApi';

const { Title } = Typography;

export default function Dashboard() {
  // 获取全局用户状态
  const { initialState } = useModel('@@initialState');

  // 状态管理
  const [loading, setLoading] = useState(false);
  const [statistics, setStatistics] = useState<any>({
    userStats: null,
    courseStats: null,
    contentStats: null,
    systemStats: null,
  });

  // 获取统计数据
  const fetchStatistics = async () => {
    setLoading(true);
    try {
      const [userStatsRes, courseStatsRes, contentStatsRes, systemStatsRes] = await Promise.all([
        getUserStatistics({
          start_date: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          end_date: new Date().toISOString().split('T')[0],
        }),
        getCourseStatistics({
          start_date: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          end_date: new Date().toISOString().split('T')[0],
        }),
        getContentStatistics({
          start_date: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          end_date: new Date().toISOString().split('T')[0],
        }),
        getSystemStatistics({
          start_date: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          end_date: new Date().toISOString().split('T')[0],
        }),
      ]);

      setStatistics({
        userStats: userStatsRes.code === 200 ? userStatsRes.data : null,
        courseStats: courseStatsRes.code === 200 ? courseStatsRes.data : null,
        contentStats: contentStatsRes.code === 200 ? contentStatsRes.data : null,
        systemStats: systemStatsRes.code === 200 ? systemStatsRes.data : null,
      });
    } catch (error) {
      console.error('获取统计数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStatistics();
  }, []);

  // 用户增长趋势图表配置
  const userGrowthConfig = {
    data: statistics.userStats?.growth_trend || [],
    xField: 'date',
    yField: 'count',
    smooth: true,
    areaStyle: () => ({ fill: 'l(270) 0:#ffffff 0.5:#7ec2f3 1:#1890ff' }),
  };

  // 学习完成率图表配置
  const learningCompletionConfig = {
    data: statistics.courseStats?.completion_trend || [],
    xField: 'date',
    yField: 'completion_rate',
    smooth: true,
    color: '#52c41a',
  };

  // 内容类型分布图表配置
  const contentTypeConfig = {
    data: statistics.contentStats?.type_distribution || [],
    angleField: 'count',
    colorField: 'type',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name} {percentage}%',
    },
  };

  // 系统性能图表配置
  const systemPerformanceConfig = {
    data: statistics.systemStats?.performance_trend || [],
    xField: 'date',
    yField: 'response_time',
    smooth: true,
    color: '#fa8c16',
  };

  return (
    <PageContainer
      header={{
        title: '推普活动管理系统 - 仪表盘',
        extra: (
          <Button type="primary" onClick={fetchStatistics} loading={loading}>
            刷新数据
          </Button>
        ),
      }}
    >
      {/* 用户信息显示 */}
      {initialState?.currentUser && (
        <Card style={{ marginBottom: 16 }}>
          <Alert
            message={`欢迎回来，${initialState.currentUser.nickname || initialState.currentUser.username}！`}
            description={
              <div>
                <p>角色：{initialState.currentUser.role === 'admin' ? '超级管理员' : initialState.currentUser.role}</p>
                <p>状态：{initialState.currentUser.status === 'active' ? '正常' : initialState.currentUser.status}</p>
                <p>最后登录：{initialState.currentUser.last_login_at ? new Date(initialState.currentUser.last_login_at).toLocaleString() : '首次登录'}</p>
              </div>
            }
            type="success"
            showIcon
          />
        </Card>
      )}

      {/* 核心指标概览 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={statistics.userStats?.total_users || 0}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="课程总数"
              value={statistics.courseStats?.total_courses || 0}
              prefix={<BookOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="内容总数"
              value={statistics.contentStats?.total_content || 0}
              prefix={<FileTextOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="今日活跃用户"
              value={statistics.userStats?.active_users_today || 0}
              prefix={<HeartOutlined />}
              valueStyle={{ color: '#eb2f96' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 学习数据概览 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="课程完成率"
              value={statistics.courseStats?.completion_rate || 0}
              suffix="%"
              prefix={<TrophyOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="平均学习时长"
              value={statistics.courseStats?.avg_study_time || 0}
              suffix="分钟"
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="内容浏览量"
              value={statistics.contentStats?.total_views || 0}
              prefix={<EyeOutlined />}
              valueStyle={{ color: '#13c2c2' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="系统响应时间"
              value={statistics.systemStats?.avg_response_time || 0}
              suffix="ms"
              prefix={<BarChartOutlined />}
              valueStyle={{ color: '#fa541c' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 数据趋势图表 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} md={12}>
          <Card title="用户增长趋势" loading={loading}>
            <EchartsArea height={300} {...userGrowthConfig} />
          </Card>
        </Col>
        <Col xs={24} md={12}>
          <Card title="学习完成率趋势" loading={loading}>
            <EchartsLine height={300} {...learningCompletionConfig} />
          </Card>
        </Col>
      </Row>

      {/* 内容分析和系统监控 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} md={12}>
          <Card title="内容类型分布" loading={loading}>
            <EchartsPie height={300} {...contentTypeConfig} />
          </Card>
        </Col>
        <Col xs={24} md={12}>
          <Card title="系统性能趋势" loading={loading}>
            <EchartsLine height={300} {...systemPerformanceConfig} />
          </Card>
        </Col>
      </Row>

      {/* 快速操作面板 */}
      <Card title="快速操作" style={{ marginTop: 24 }}>
        <Space size="large" wrap>
          <Button type="primary" icon={<UserOutlined />} href="/user-management/user-list">
            用户管理
          </Button>
          <Button type="primary" icon={<BookOutlined />} href="/course-management/course-list">
            课程管理
          </Button>
          <Button type="primary" icon={<FileTextOutlined />} href="/content-management/banner-list">
            内容管理
          </Button>
          <Button type="primary" icon={<BarChartOutlined />} href="/data-statistics/user-stats">
            数据统计
          </Button>
        </Space>
      </Card>

      {/* 系统状态信息 */}
      <Card title="系统状态" style={{ marginTop: 16 }}>
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="数据库连接"
              value="正常"
              valueStyle={{ color: '#52c41a' }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="缓存状态"
              value="正常"
              valueStyle={{ color: '#52c41a' }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="存储空间"
              value={statistics.systemStats?.storage_usage || 0}
              suffix="%"
              valueStyle={{ color: statistics.systemStats?.storage_usage > 80 ? '#cf1322' : '#52c41a' }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="内存使用"
              value={statistics.systemStats?.memory_usage || 0}
              suffix="%"
              valueStyle={{ color: statistics.systemStats?.memory_usage > 80 ? '#cf1322' : '#52c41a' }}
            />
          </Col>
        </Row>
      </Card>
    </PageContainer>
  );
}